#include "app_common.h"
#include <stddef.h>
#include "MQTTClient.h"
#include "app_mqtt.h"
#include "log/log.h"
/*定义接受处理消息数据的回调函数指针*/
static CallBack recv_callback = NULL;

static MQTTClient client;
static MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
static MQTTClient_message pubmsg = MQTTClient_message_initializer;

// 发送消息完成的回调函数
void delivered(void *context, MQTTClient_deliveryToken dt)
{
    printf("Message with token value %d delivery confirmed\n", dt);
}
// 接收到远程发送过来的消息
// 这个函数返回值有点特别: return 1:执行成功，return 0:执行失败
int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
    int result = -1;
    printf("Message arrived\n");
    if (recv_callback != NULL)
    {
        /*接受到远程发来的数据，执行回调函数*/
        result = recv_callback((char *)message->payload, message->payloadlen) == 0 ? 1 : 0;
    }
    MQTTClient_freeMessage(&message);
    MQTTClient_free(topicName);
    return result;
}

// 连接断开时的回调函数
void connlost(void *context, char *cause)
{
    printf("\nConnection lost\n");
    printf("   cause: %s\n", cause);
}

/**
 * @brief 初始化mqtt客户端
 */
int app_mqtt_init(void)
{
    int result = -1;
    // 创建MQTT客户端
    if ((result = MQTTClient_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL)) != MQTTCLIENT_SUCCESS)
    {
        log_error("fail to create MQTT client");
        return -1;
    }
    // 设置回调函数
    if ((result = MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered)) != MQTTCLIENT_SUCCESS)
    {
        log_error("fail to register callback funcation");
        MQTTClient_destroy(&client);
        return -1;
    }
    // 连接mqtt服务器
    if ((result = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
    {
        log_error("Failed to connect, return code %d", result);
        MQTTClient_destroy(&client);
        return -1;
    }
    // 订阅主题（PULL）
    if ((result = MQTTClient_subscribe(client, TOPIC_PULL, QOS)) != MQTTCLIENT_SUCCESS)
    {
        printf("Failed to subscribe, return code %d", result);
        MQTTClient_disconnect(client, TIMEOUT);
        MQTTClient_destroy(&client);
        return -1;
    }
    return 0;
}

/**
 * @brief 关闭mqtt客户端
 */
void app_mqtt_close(void)
{
    MQTTClient_unsubscribe(client, TOPIC_PULL);
    MQTTClient_disconnect(client, TIMEOUT);
    MQTTClient_destroy(&client);
}

/**
 * @brief 发送消息
 */
int app_mqtt_send(char *data, int len)
{
    int result = -1;
    pubmsg.payload = data;
    pubmsg.payloadlen = len;
    pubmsg.qos = QOS;
    // 发布消息
    if ((result = MQTTClient_publishMessage(client, TOPIC_PUSH, &pubmsg, NULL)) != MQTTCLIENT_SUCCESS)
    {
        printf("Failed to publish message, return code %d\n", result);
        return -1;
    }
    return 0;
}

/*注册回调函数*/
void app_mqtt_registerRecvCallBack(CallBack callback)
{
    recv_callback = callback;
}